﻿using System;
using System.Web;
using System.Web.Security;

namespace OneWorks.Web.Common
{
    /// <summary>
    /// 身份验证
    /// </summary>
    public static class FormsAuth
    {            
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="data">存储用户信息</param>
        /// <param name="expireMin">过期分钟</param>
        public static void SignIn(string loginName, string data, int expireMin)
        {   
            //创建一个FormsAuthenticationTicket，它包含登录名以及额外的用户数据。
            var ticket = new FormsAuthenticationTicket(2,
                loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);

            //加密Ticket，变成一个加密的字符串。
            var cookieValue = FormsAuthentication.Encrypt(ticket);

            //根据加密结果创建登录Cookie
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Domain = FormsAuthentication.CookieDomain,
                Path = FormsAuthentication.FormsCookiePath
            };
            if (expireMin > 0)
                cookie.Expires = DateTime.Now.AddMinutes(expireMin);

            var context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException();

            //写登录Cookie
            context.Response.Cookies.Remove(cookie.Name);
            context.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 登出
        /// </summary>
        public static void SingOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}
